<html>
<head>
  <link href="style.css" rel="stylesheet" type="text/css"/>
  <script src="jquery.js"></script>
  <script>
    var locale = chrome.i18n.getMessage; // Short-hand

    var waiting = false;

    var msg_body = "";

    function requestList(now){
        clearRows("list", 1);
        clearRows("msgList", 1);
        $("#list").append("<tr><th colspan='2'><img src='ajax-loader.gif'></img></td></tr>");
        $("#msgList").append("<tr><th colspan='3'><img src='ajax-loader.gif'></img></th></tr>");
        if(!now)
          now = false;
        chrome.extension.sendRequest({type: "friendsList",now:now}, function(response) {
          if(response.ok){
                responseRecieved(response);
          }
          else
              waiting = true;
        });
    }
    function clearRows(id, remaining){
        var elem = document.getElementById(id);
        while(elem.rows.length > remaining){
           elem.deleteRow(remaining);
        }
    }


    chrome.extension.onRequest.addListener(
        function(request, sender, sendResponse) {
            if(waiting && request.type=="waitingList"){
                responseRecieved(request);
                waiting = false;
            }
            sendResponse();
    });
 
    function responseRecieved(data){
        document.getElementById("list").deleteRow(1);
        document.getElementById("msgList").deleteRow(1);
        $("#list").append(data.list);
        $("#msgList").append(data.msgList);
        refreshUI();
    }

    $(document).ready(function (){

      // --Localization--
      $("a[id='myXboxLink']").html(locale("myXbox"));
      $("a[id='friendsLink']").html(locale("friends"));
      $("a[id='messagesLink']").html(locale("msgs"));
      $("a[id='msgBoxTabHead']").html(locale("sendmsg"));

      $("#msgForm_toText").html(locale("msgForm_to"));
      $("#msgForm_send").html(locale("msgForm_send"));
      $("#msgForm_clear").html(locale("msgForm_clear"));

      $("#list").html("<tr><th>" + locale("gTag") + "</th><th>" + locale("info_short") + "</th></tr>");
      $("#msgList").html("<tr><th colspan='2' >" + locale("gTag") + "</th><th>" + locale("msg") + "</th></tr>");
      
      if(localStorage["msgForm_to"])
         $("#msgForm_to")[0].value = localStorage["msgForm_to"];
      if(localStorage["msgForm_text"])
         $("#msgForm_text")[0].value = localStorage["msgForm_text"];

      refreshUI();
      requestList();
    });


    function refreshUI(){
        $("a").each(function (){
            if(this.href.indexOf("chrome.tabs") < 0 && this.href.indexOf("javascript:") < 0)
                this.href = "javascript:chrome.tabs.create({url:\"" + this.href + "\"})"
        });
        $("#list tr:odd").css("background-color", "#eeeeec");
	$("#msgList tr:nth-child(4n+2)").css("background-color", "#eeeeec");
    }

    function openMsg(id,obj){
        
        var msgBody = $(obj).parent().parent().next();
        if(msgBody.text().length <= 0){
            $(obj).parent().parent().find(".loadingMsg").toggle();
            msgBody.load("http://live.xbox.com/profile/MessageCenter/ViewMessage.aspx?mx=" + id + " .XbcMessageTextPanel",function(){
                $(this).prev().find(".loadingMsg").toggle();
                $("#msgList").find(".msgBody:visible").toggle();
                $(this).html("<td colspan='3'><hr>" + 
                            $(this).text() + 
                            "<br><a href='javascript:void(0);' onclick='msgForm_reply(this)' style='text-decoration:none;'><b>[" + 
                            locale("msg_reply") + "]</b></a> - " +
                            "<a href='javascript:void(0);' onclick='msg_delete(this)' style='text-decoration:none;'><b>[" +
                            locale("msg_delete") + "]</b><hr></td>");
                $(this).toggle();
            });
        }
        else
          msgBody.toggle();
    }

    function toggleDisplay(show, sender){
        $(".tabHead a").not(sender).attr("class", "tabHeadNotSelected");
        $(sender).attr("class", "tabHeadSelected");
        $(".tableCont div:visible").not($("#" + show).parent()).slideToggle();
        $(".tableCont div:hidden").filter($("#" + show).parent()).slideToggle();
    }

    function onlineOver(obj){
      obj = $(obj);
      var temp = obj.attr("title");
      obj.attr("title", obj.text());
      obj.html(temp);
    }
    function onlineOut(obj){
      onlineOver(obj);
    }
    var closeOnClick = true;
    function gamertagClick(obj,evt){
        var online = $(obj).parent().parent().attr("class").indexOf("Online") > 0;
        $("#overlay").html("<span>" +
                                $(obj).text() + " - " +
                                "<span style='color:" + (online ? "#4e9a06" : "#a40000") + "'>" +
                                    (online ? "ONLINE" : "OFFLINE") + 
                                "</span>" +
                           "</span><br>" +
                           "<a href='javascript:void(0);' onclick=\"$('#overlay').hide(); msgForm_newMessage('" + $(obj).text() +  "');\">" +
                                locale("sendmsg") +
                           "</a> - " +
                           "<a href='http://live.xbox.com/profile/profile.aspx?GamerTag=" + escape($(obj).text()) + "'>" +
                                locale("viewprofile") +
                           "</a><br>" +
                           "<img style='padding-top:2px;' src='http://card.mygamercard.net/" + escape($(obj).text()) +  ".png'></img>")
        .show();
        refreshUI();
        return false;
    }
    function bodyClick(){
        if(closeOnClick)
            $("#overlay").hide();
    }

    function msg_delete(el){
        var id = $(el).parent().parent().prev().find(".msg_idCont").text(); 
        var url = "http://live.xbox.com/en-US/profile/MessageCenter/RemoveMessage.aspx?mx=" + id + "&bk=0";
        $(el).parent().parent().prev().find(".loadingMsg").toggle();
        $.get(url, function(){
            var i = this.url.split("?")[1].split("=")[1].split("&")[0];
            console.log(i);
            var el = $(".msg_idCont:contains('" + i + "')")[0];
            console.log(el);
            $(el).parent().parent().next().detach();
            $(el).parent().parent().detach();
            chrome.extension.sendRequest({type:"deleteMessage",id:i});
        });
        
    }
    function msgForm_change(){
        var area = $("#msgForm_text")[0];
        localStorage["msgForm_to"] = $("#msgForm_to")[0].value;
        localStorage["msgForm_text"] = area.value;
        $("#msgForm_chars").html(area.value.length+"/250");
        if($("#msgForm_to")[0].value.length > 0)
            $("#msgForm_to").css({"backgroundColor":"#8ae234"});
        else
        {
            $("#msgForm_to").css({"backgroundColor":"#ef2929"});
            return false;
        }
        if(area.value.length <= 250){
            $("#msgForm_chars").css({"color":"#4e9a06"});
            return true;
        }
        else
        {
            $("#msgForm_chars").css({"color":"#a40000"});
            return false;
        }
    }
    function msgForm_submit(){
        var text = $("#msgForm_text")[0].value;
        var to = $("#msgForm_to")[0].value;
        if(to.length > 0)
            $("#msgForm_to").css({"backgroundColor":"#8ae234"});
        else
        {
            $("#msgForm_to").css({"backgroundColor":"#ef2929"});
            return false;
        }
        if(text > 250){
            $("#msgForm_chars").css({"color":"#a40000"});
            $("#msgForm_chars").html(locale("msgForm_tooMany"));
            return false;
        }
        var url = "http://live.xbox.com/profile/MessageCenter/SendMessage.aspx?gt=" + escape(to);
        msg_body = escape(text);
        $("#msgForm_send")[0].value = locale("msgForm_sending");
        $("#msgForm_send")[0].disabled = true;
        chrome.tabs.create({url:url,selected:false}, function(tab){
            chrome.tabs.executeScript(tab.id, {code:"/*alert(\"" + msg_body + "\");*/ var el = document.getElementById('ctl00_MainContent_composeMessageControl_messageTextBox'); el.value=unescape('" + msg_body + "'); document.forms[1].elements[6].disabled = false; document.forms[1].elements[6].click();"}, function(){
                    var t = setTimeout("msgForm_closeTab(" + this.args[0] + ")", 500);
                });
        });
    }
    function msgForm_reply(el){
        var to = $(el).parent().parent().prev().find("td").eq(1).text();
        var re = $(el).parent().parent().prev().find("td").eq(2).text();
        $("#msgForm_to")[0].value = to;
        $("#msgForm_text")[0].value = "RE: " + re + "\n";
        toggleDisplay('msgBox', $("#msgBoxTabHead")[0]);
        $("#msgForm_text")[0].focus();
        $("#msgForm_text")[0].select();
    }
    function msgForm_newMessage(gamertag){
        $("#msgForm_to")[0].value = gamertag;
        $("#msgForm_text")[0].value = "";
        toggleDisplay('msgBox', $("#msgBoxTabHead")[0]);
        $("#msgForm_text")[0].focus();
        $("#msgForm_text")[0].select();
    }
    function msgForm_closeTab(id){
        chrome.tabs.update(id, {selected:false}, function(tab){
            console.log(tab.status);
            if(tab.status == "complete"){
                $("#msgForm_send")[0].disabled = false;
                $("#msgForm_send").html(locale("msgForm_send"));
                chrome.tabs.remove(this.args[0]);
            }
            else{
                var text = $("#msgForm_send").html();
                $("#msgForm_send").html((locale("msgForm_sending").length == text.length+3) ? locale("msgForm_sending") : text + ".");
                var t = setTimeout("msgForm_closeTab(" + this.args[0] + ")", 500);
            }
        });
    }  
    function msgForm_clear(){
        $("#msgForm_to")[0].value = "";
        $("#msgForm_text")[0].value = "";
        msgForm_change();
    }
  </script>
</head>
<body onclick="bodyClick();">
<div id="drop" style="display:none;visibility:hidden;"></div>
<div id="content">
    <div align="center" id="topLinks" style="padding-bottom: 2px;"><a href="http://live.xbox.com/default.aspx" id="myXboxLink">My Xbox</a> - <a id="friendsLink" href="http://live.xbox.com/profile/Friends.aspx">Friends</a> - <a id="messagesLink" href="http://live.xbox.com/profile/MessageCenter/ViewMessages.aspx">Messages</a></div>
    <div>
        <div class="tabHead">
            <a href='javascript:;' id="friendsLink" class="tabHeadSelected" onclick="toggleDisplay('list', this);">Friends</a>
            <a href='javascript:;' id="messagesLink" class="tabHeadNotSelected" onclick="toggleDisplay('msgList', this);">Messages</a>
            <a href='javascript:;' id="msgBoxTabHead" class="tabHeadNotSelected" onclick="toggleDisplay('msgBox', this);">Send Message</a>
        </div>
        <div class="tableCont">
            <div>
                <div id="overlay" style="display:none;"  onmouseout="closeOnClick=true;" onmouseover="closeOnClick=false"></div>
                <table id="list"></table>
            </div>
            <div style="display:none;">
                <table id="msgList"></table>
            </div>
            <div style="display:none;">
                <table id="msgBox">
                    <tr><th width="25%"><span id="msgForm_toText">To</span>:</th><th width="75%" style="text-align:left;"><input id="msgForm_to" onchange="return msgForm_change();" /></th></tr>
                    <tr><td colspan="2"><textarea rows="8" cols="32" id="msgForm_text" onkeyup="return msgForm_change();" onchange="return msgForm_change();"></textarea></td></tr>
                    <tr><td style="text-align:right"><span id="msgForm_chars">0/250</span></td><td><button id="msgForm_send" onclick="msgForm_submit();">Send</button><button id="msgForm_clear" onclick="msgForm_clear();">Clear</button></td></tr>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>
